package com.haven.webrobotserver.controller;

import com.alibaba.fastjson.JSONObject;
import com.haven.webrobotserver.domain.TestcaseTestdata;
import com.haven.webrobotserver.domain.Testplan;
import com.haven.webrobotserver.service.TestcaseTestdataService;
import com.haven.webrobotserver.service.TestplanService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/testplan")
@CrossOrigin("http://localhost:8080")
public class TestplanController {

    @Autowired
    private TestplanService testplanService;
    @Autowired
    private TestcaseTestdataService testcaseTestdataService;

    private final org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());

    @PostMapping("/getTestplanList")
    public JSONObject getTestplanList(@RequestBody Map<String,String> queryForm){

        JSONObject result = new JSONObject();

        try{
            List<Map<String, String>> testplanList = testplanService.getTestplanList(queryForm);
            result.put("data",testplanList);
            result.put("status",200);
        }catch (Exception e){
            e.printStackTrace();
            result.put("status",500);
        }
        return result;
    }

    @PostMapping("/newTestplan")
    public JSONObject newTestplan(@RequestBody Map<String,Object> params){
        JSONObject result = new JSONObject();
        logger.info(params.toString());

        /*取参数封装testplan入库*/
        Testplan testplan = new Testplan();

        String name = (String)params.get("name");
        String description = (String)params.get("description");
        int projectId = (int)params.get("projectId");

        testplan.setName(name);
        testplan.setDescription(description);
        testplan.setProjectId(projectId);

        testplanService.insertOne(testplan);
        logger.info("testplan's id is: "+testplan.getId());

        List<Map<String,Object>> tts = (List<Map<String,Object>>)params.get("testcaseTestdata");

        for(Map<String,Object> tt:tts){
            TestcaseTestdata testcaseTestdata = new TestcaseTestdata();
            testcaseTestdata.setTestplanId(testplan.getId());

            int testcaseId = (int)tt.get("testcaseId");
            int testdataId = (int)tt.get("testdataId");
            testcaseTestdata.setTestcaseId(testcaseId);
            testcaseTestdata.setTestdataId(testdataId);
            testcaseTestdataService.insertOne(testcaseTestdata);
        }

        result.put("status",200);
        return result;
    }

}
